package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.R;
import com.gaohe.pojo.Category;
import com.gaohe.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    //分页查询
    @GetMapping("/page")
    public R<Page<Category>> page(Integer page, Integer pageSize) {
//        log.info("{},{}",page,pageSize);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper();
        //先按sort排序，然后再按更新时间排序
        lqw.orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime);
        Page<Category> page1 = new Page(page, pageSize);
        categoryService.page(page1, lqw);
        return R.success(page1);
    }

    //新增数据
    @PostMapping
    public R<String> addDish(@RequestBody Category category) {
//        log.info("{}", category);
        categoryService.save(category);
        return R.success("菜品新增成功");
    }

    //删除数据
    @DeleteMapping
    public R<String> deleteCategory(Long id) {
        categoryService.removeById(id);
        return R.success("删除成功");
    }

    //修改数据
    @PutMapping
    public R<String> updateCategory(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    //新增菜品时的菜品分类
    @GetMapping("/list")
    public R<List<Category>> list(Integer type) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper();
        lqw.eq(type != null, Category::getType, type);
        List<Category> categoryList = categoryService.list(lqw);
        return R.success(categoryList);
    }
}
